package com.kalaqia.image.di.observable;

import android.graphics.Bitmap;
import android.os.Looper;

import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

import java.util.concurrent.atomic.AtomicBoolean;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.disposables.Disposables;

/**
 * function:
 * project:kalaqia
 * describe:
 * created owner:kalaqia 421407393@qq.com
 * created date:2017/8/4 14:15
 */
//<editor-fold desc="version update log">
// update owner:kalaqia  421407393@qq.com
// update datetime:2017/8/4 14:15
// update remark:
//</editor-fold>
public class SimpleTargetObservable extends Observable<Bitmap> {

    private final RequestBuilder builder;

    public SimpleTargetObservable(RequestBuilder builder) {
        this.builder = builder;
    }

    private static boolean checkMainThread(Observer<?> observer) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            observer.onSubscribe(Disposables.empty());
            observer.onError(new IllegalStateException(
                    "Expected to be called on the main thread but was " + Thread.currentThread().getName()));
            return false;
        }
        return true;
    }

    @Override
    protected void subscribeActual(Observer<? super Bitmap> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        SimpleTargetDisposable disposable = new SimpleTargetDisposable(observer);
        observer.onSubscribe(disposable);
        this.builder.into(disposable);
    }

    private final class SimpleTargetDisposable extends SimpleTarget<Bitmap> implements Disposable {

        private final Observer<? super Bitmap> observer;

        SimpleTargetDisposable(Observer<? super Bitmap> observer) {
            this.observer = observer;
        }

        private final AtomicBoolean unsubscribed = new AtomicBoolean();

        @Override
        public void onResourceReady(Bitmap t, Transition<? super Bitmap> transition) {
            if (!isDisposed()) {
                observer.onNext(t);
            }
        }

        @Override
        public void dispose() {

        }

        @Override
        public boolean isDisposed() {
            return unsubscribed.get();
        }
    }

}
